﻿package {
	
	import flash.display.Sprite;
	import flash.net.Socket;
	import flash.events.*;
	import flash.system.Security;
	import flash.display.MovieClip;

	public class SocketExample extends MovieClip
	{
		private var ip = "dreigon-mc.hopto.org";
		private var port = 25565;
		
		private var mysocket:Socket;
		private var username:String;
		private var loggedIn:Boolean = false;
	
		public function SocketExample():void
		{
			login.addEventListener(MouseEvent.CLICK, loginListener);
			mysocket = new Socket();
			Security.allowDomain("*");
			mysocket.addEventListener(Event.CONNECT, onConnect);
			mysocket.addEventListener(Event.CLOSE, onClose);
			mysocket.addEventListener(IOErrorEvent.IO_ERROR, onError);
			mysocket.addEventListener(ProgressEvent.SOCKET_DATA, onResponse);
			mysocket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecError);
			input.addEventListener(KeyboardEvent.KEY_DOWN, keyListener);
			sendBtn.addEventListener(MouseEvent.CLICK,sendCommand);
		}
	
		private function loginListener(e:Event) {
			username = usernameField.text;
			if(username == "") username = "user" + int(Math.random() * 1000);
			mysocket.connect(ip,port);
			changeView();
			loggedIn = true;
		}
		
		private function changeView() {
			login.x += 600;
			usernameField.x += 600;
			userLabel.x += 600;
			input.x -= 600;
			output.x -= 600;
			sendBtn.x -= 600;
		}
	
		private function keyListener(e:KeyboardEvent) {
			if (e.keyCode == 13) {
				if (loggedIn) sendCommand(e);
				else loginListener(e);
			}
		}
		
		private function sendCommand(e:Event):void {
			if (input.text != "") {
				mysocket.writeUTFBytes(username + ": " + input.text + "\n");
				mysocket.flush();
				input.text = "";
			}
		}
	
		private function onConnect(e:Event):void
		{
			output.appendText("Connection OK\n");
		}
	
		private function onClose(e:Event):void
		{
			// Security error is thrown if this line is excluded
			mysocket.close();
		}
	
		private function onError(e:IOErrorEvent):void
		{
			trace("IO Error: "+e);
		}
	
		private function onSecError(e:SecurityErrorEvent):void
		{
			trace("Security Error: "+e);
		}
	
		private function onResponse(e:ProgressEvent):void
		{
			if (mysocket.bytesAvailable > 0)
			{
				output.appendText(mysocket.readUTFBytes(mysocket.bytesAvailable));
			}
		}
	}
}